import { _decorator, Component, EPhysics2DDrawFlags, Input, Node, PhysicsSystem2D, RigidBody2D, tween, Tween, Vec2, Vec3 } from 'cc';
import { BaseComponent } from '../../Manager/UIManager/BaseComponent';
const { ccclass, property } = _decorator;

@ccclass('GameScene')
/**
 * 游戏场景
 */
export class GameScene extends BaseComponent {

    //操作层
    @property(Node)
    private TouchLoad: Node = null;

    //球
    @property(Node)
    private Ball: Node = null;

    //球阴影
    @property(Node)
    private BallShadow: Node = null;

    //跳跃速度
    private JumpSpeed: number = 50;

    //是否是左侧
    private IsLeft: boolean = true;

    //左侧篮板
    @property(Node)
    private LeftBoard: Node = null;

    //右侧篮板
    @property(Node)
    private RightBoard: Node = null;


    protected Init(): void {
        PhysicsSystem2D.instance.debugDrawFlags = EPhysics2DDrawFlags.Aabb |
            EPhysics2DDrawFlags.Pair |
            EPhysics2DDrawFlags.CenterOfMass |
            EPhysics2DDrawFlags.Joint |
            EPhysics2DDrawFlags.Shape;
        this.TouchLoad.on(Input.EventType.TOUCH_START, this.TouchCb, this);
    }

    protected OnShow(): void {
        this.GameStart();
    }

    /**
     * 游戏开始
     */
    public GameStart() {
        this.IsLeft = true;
        this.RightBoard.setPosition(new Vec3(1000, 0));
        this.LeftBoard.setPosition(new Vec3(-1000, 0));
        this.LeftBoardShow();
    }

    /**
     * 左侧篮板出现
     */
    private LeftBoardShow() {
        Tween.stopAllByTarget(this.LeftBoard);
        let pos_y: number = -300 + Math.random() * 600;
        this.LeftBoard.setPosition(new Vec3(-1000, pos_y));
        tween(this.LeftBoard).to(0.3, { position: new Vec3(-350, pos_y) }).start();
    }

    /**
     * 用户点击
     */
    private TouchCb() {
        this.Ball.getComponent(RigidBody2D).linearVelocity = new Vec2(this.IsLeft ? -10 : 10, this.JumpSpeed)
    }

    protected update(dt: number): void {
        if (this.Ball.getPosition().x <= -400) {
            this.Ball.setPosition(375, this.Ball.getPosition().y);
        } else if (this.Ball.getPosition().x >= 400) {
            this.Ball.setPosition(-375, this.Ball.getPosition().y);
        }

        this.BallShadow.setPosition(this.Ball.getPosition().x, 0);
    }

}


